package com.ld.config;

import com.ld.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private MyUserDetailService userDetailService;
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//1. 自定义登录表单
		http.formLogin()
				.loginPage("/user/login")               // 登录页面
				.loginProcessingUrl("/login")           // 登录处理页（自己定义名称，由系统完成）
				.successForwardUrl("/user/welcome");    // 登录成功后的跳转页面

		http.authorizeRequests()
			.antMatchers("/user/hello","/webjars/**") // 要放行的页面
			.permitAll()
			.anyRequest()                                        // 任意其它请求
			.authenticated();                                    // 一律需要认证

		// 关闭 csrf
		http.csrf().disable();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 自定义认证规则
		auth.userDetailsService(userDetailService).passwordEncoder(encoder());
	}

	@Bean
	public BCryptPasswordEncoder encoder(){
		return new BCryptPasswordEncoder();
	}
}
